import { Controller, UploadedFile, UploadedFiles, UseInterceptors, Post} from '@nestjs/common';
import { UploadService } from './upload.service';
import { CreateUploadDto } from './dto/create-upload.dto';
import { UpdateUploadDto } from './dto/update-upload.dto';

import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express'
import { diskStorage } from 'multer';
import { extname, join } from 'path';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) { }

  // 单文件上传
  @Post('single')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads', // 保存文件的路径
        filename: (req, file, callback) => {
          const uniqueSuffix = new Date().getTime();
          callback(null, `${uniqueSuffix}${extname(file.originalname)}`);
        },
      }),
      // 文件类型选择
      // fileFilter: (req, file, callback) => {
      //   if (!file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
      //     return callback(new Error('Only image files are allowed!'), false);
      //   }
      //   callback(null, true);
      // },
    }),
  )
  uploadSingle(@UploadedFile() file: Express.Multer.File) {
    return this.uploadService.handleUpload(file);
  }

  // 多文件上传
  @Post('multiple')
  @UseInterceptors(
    FilesInterceptor('files', 10, { // 限制最多上传 10 个文件
      storage: diskStorage({
        destination: './uploads',
        filename: (req, file, callback) => {
          console.log('req',req)
          console.log('file',file)
          const uniqueSuffix = new Date().getTime();
          callback(null, `${uniqueSuffix}${extname(file.originalname)}`);
        },
      }),
      // fileFilter: (req, file, callback) => {
      //   if (!file.mimetype.match(/\/(jpg|jpeg|png|gif)$/)) {
      //     return callback(new Error('Only image files are allowed!'), false);
      //   }
      //   callback(null, true);
      // },
    }),
  )
  uploadMultiple(@UploadedFiles() files: Express.Multer.File[]) {
    return this.uploadService.handleMultipleUpload(files);
  }
}
